package com.changli01.example;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class reflectionTest {
    @Test

    //不用反射的做法
    public void test() {
        Person p1 = new Person();
        p1.age = 20;
        p1.show();



    }

    @Test
    //使用反射
    public void test2() throws Exception {

        Class clazz = Person.class;
        Person p1 = (Person) clazz.newInstance();
//        System.out.println(p1.age);
//        System.out.println(clazz.getField(p1.name));
        Field agefield = clazz.getField("age");
        agefield.set(p1,10);
        System.out.println(agefield.get(p1));


        Method methodShow = clazz.getMethod("show");
        methodShow.invoke(p1);


    }

    @Test
    public void test3() throws Exception {
        Class clazz = Person.class;
        Person p1 = (Person) clazz.newInstance();

        Field nation = clazz.getDeclaredField("nation");
        nation.setAccessible(true);//IllegalAccessException
        nation.set(p1,"CHINA");
        System.out.println(nation.get(p1));

    }



}
